import {
  _decorator,
  Animation,
  AudioClip,
  CCString,
  Collider2D,
  Component,
  Contact2DType,
  Node,
  Prefab,
  Sprite,
} from "cc";
import { Bullet } from "./Bullet";
import { GameManager } from "./GameManager";
import { EnemyManage } from "./EnemyManage";
import { AudioMgr } from "./AudioMgr";
const { ccclass, property } = _decorator;

@ccclass("Enemy")
export class Enemy extends Component {
  @property
  public speed: number = 300;

  @property({
    type: Animation,
  })
  public animation: Animation = null;

  @property
  public hp: number = 1;

  @property
  public animHit: string = "";

  @property
  public animDown: string = "";

  @property
  public score: number = 1;

  @property(AudioClip)
  public enemyAudio: AudioClip = null;

  public collider: Collider2D = null;

  protected start() {
    this.collider = this.getComponent(Collider2D);
    if (this.collider) {
      this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  protected update(deltaTime: number) {
    if (this.hp > 0) {
      this.node.setPosition(
        this.node.position.x,
        this.node.position.y - this.speed * deltaTime,
        this.node.position.z
      );
    }

    // 超出屏幕边界销毁
    if (this.node.position.y < -580) {
      this.node.destroy();
    }
  }

  protected onDestroy(): void {
    // 移除碰撞回调
    this.collider &&
      this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    EnemyManage.getInstance().removeEnemy(this.node);
  }

  /**
   * 子弹和敌机碰撞回调
   * @param selfCollider
   * @param otherCollider
   */
  onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    this.hp -= 1;

    // 检测碰撞体是否是子弹
    // 或者otherCollider.name === "bullet"
    // 或者otherCollider.getComponent("Bullet")
    if (otherCollider.getComponent(Bullet)) {
      otherCollider.enabled = false;
      // otherCollider.node.destroy(); 控制台会有一场告警
      otherCollider.getComponent(Sprite).enabled = false;
    }

    if (this.hp > 0) {
      this.animation.play(this.animHit);
    } else {
      this.animation.play(this.animDown);
    }

    // 敌机血量为0时销毁
    if (this.hp <= 0) {
      this.dead();
    }
  }

  private haveDead: boolean = false;
  public dead() {
    if (this.haveDead) return;
    if (this.enemyAudio) {
      AudioMgr.inst.playOneShot(this.enemyAudio, 0.2);
    }
    GameManager.getInstance().addScore(this.score);
    if (this.collider) {
      this.collider.enabled = false;
    }
    this.scheduleOnce(() => {
      this.node.destroy();
    }, 1);
    this.haveDead = true;
  }

  public killNow() {
    if (this.hp <= 0) return;
    this.hp = 0;
    this.animation.play(this.animDown);
    this.dead();
  }
}
